package com.pay.wx;


import common.ClientUtils;
import common.WXPayUtils;
import org.apache.http.client.ClientProtocolException;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 微信支付~~服务商支付
 *
 * @author chen
 */
public class WxPayMicropay {

    private WXConfig wxConfig;

    public WxPayMicropay(WXConfig wxConfig) {
        this.wxConfig = wxConfig;
    }


    /**
     * 微信支付处理
     *
     * @param orderNum  订单id
     * @param money     订单金额
     * @param openId    子商户号的openid
     * @param attach    附加数据
     * @param body      商品描述
     * @param suMchId   子商户号
     * @param subAPPID  子商户绑定的appid
     * @param notifyUrl 回调地址
     * @return
     */
    public Map<String, String> getWxPayValue(String orderNum, Integer money, String openId, String attach, String body, String suMchId, String subAPPID, String notifyUrl) throws Exception {
        Map<String, String> param = new HashMap<>();
        param.put("appid", wxConfig.getAppID());//公众账号ID
        param.put("mch_id", wxConfig.getMchID());//商户
        param.put("nonce_str", WXPayUtils.generateNonceStr());//随机字符串
        param.put("sub_mch_id", suMchId);//下属商户号
        param.put("attach", attach);
        param.put("body", body);
        param.put("out_trade_no", orderNum);//交易订单号
        param.put("total_fee", money.toString());//金额（分）
        param.put("sub_appid", subAPPID);
        param.put("spbill_create_ip", "127.0.0.1");//终端ip
        param.put("notify_url", notifyUrl);//通知地址
        param.put("trade_type", "JSAPI");//交易类型
        param.put("sub_openid", openId);

        String xmlParam = WXPayUtils.generateSignedXml(param, wxConfig.getKey());

        //2.发送请求
        String xmlResult = ClientUtils.doPostMethod("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlParam, "utf-8");
        //3.获取结果
        Map<String, String> mapResult = WXPayUtils.xmlToMap(xmlResult);
        if ("SUCCESS".equals(mapResult.get("return_code")) && "SUCCESS".equals(mapResult.get("result_code"))) {
            Map<String, String> repData = new LinkedHashMap<>();
            repData.put("appId", subAPPID);
            repData.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
            repData.put("nonceStr", mapResult.get("nonce_str"));
            repData.put("package", "prepay_id=" + mapResult.get("prepay_id"));

            repData.put("signType", "MD5");

            String sign = WXPayUtils.generateSignature(repData, wxConfig.getKey()); //签名
            //System.out.println("生成签名:" + sign);
            repData.put("paySign", sign);
            return repData;
        } else {
            return mapResult;
        }


    }


    /**
     * 退款处理
     *
     * @param subMchId    子商户号
     * @param refundNum   退款订单号
     * @param orderNum    订单号
     * @param orderMoney  订单金额（分）
     * @param refundMoney 退款金额（分）
     * @return
     */
    public Map<String, String> refundOrder(String subMchId, String refundNum, String orderNum, Integer orderMoney, Integer refundMoney) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", wxConfig.getAppID());
        map.put("mch_id", wxConfig.getMchID());
        map.put("sub_mch_id", subMchId);
        map.put("nonce_str", WXPayUtils.generateNonceStr());
        map.put("out_trade_no", orderNum);
        map.put("out_refund_no", refundNum);
        map.put("total_fee", orderMoney.toString());
        map.put("refund_fee", refundMoney.toString());
        try {
            String xmlParam = WXPayUtils.generateSignedXml(map, wxConfig.getKey());
            Map<String, String> resultMap = ClientUtils.certPost("https://api.mch.weixin.qq.com/secapi/pay/refund", xmlParam, wxConfig.getMchID(), wxConfig.getCertStream());
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
